package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/user-modules/api/request"
	"zg3/user-modules/internal/dao"
	"zg3/user-modules/internal/model"
	"zg3/user-modules/pkg"
)

func UserLogin(c *gin.Context) {
	var req request.UserLogin
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "请求失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.FindUserAccount(req.Account)
	if user.Id == 0 {
		user = model.User{
			Account:  req.Account,
			Password: req.Password,
		}
		if !dao.Create(&user) {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "登录注册失败",
				"data": nil,
			})
			return
		}
		token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
			ID: user.Id,
		})
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "注册登录成功",
			"data": token,
		})
		return
	}
	if user.Password != req.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
		ID: user.Id,
	})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}

func UserList(c *gin.Context) {
	var userList []model.User
	if !dao.List(&userList) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "列表展示失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户列表展示成功",
		"data": userList,
	})
	return
}

const status = "待通过"

func SendFriendReq(c *gin.Context) {
	var req request.SendFriendReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "请求失败",
			"data": err.Error(),
		})
		return
	}
	if req.ReceiveId == c.GetUint("userId") {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "不能添加自己为好友",
			"data": nil,
		})
		return
	}
	friendReq := model.FriendReq{
		SendId:    c.GetUint("userId"),
		ReceiveId: req.ReceiveId,
		Status:    status,
	}
	if !dao.Create(&friendReq) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "发送好友申请失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发送好友请求成功",
		"data": friendReq,
	})
	return
}

func AuditFriendReq(c *gin.Context) {
	var req request.AuditFriendReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "请求失败",
			"data": err.Error(),
		})
		return
	}
	var friendReq model.FriendReq
	dao.FindId(req.FriendReqId, &friendReq)
	if friendReq.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "好友申请过期",
			"data": nil,
		})
		return
	}
	if friendReq.ReceiveId != c.GetUint("userId") {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "没有权限",
			"data": nil,
		})
		return
	}

	friendReq.Status = req.Status
	dao.Update(&friendReq)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "审核完成",
		"data": false,
	})
}

func RemoveFriend(c *gin.Context) {

}
